const httpStatus = require('http-status');
const pick = require('../utils/pick');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { dietRecordService } = require('../services'); // 假设服务在 services/index.js 中导出
const mongoose = require('mongoose');

const createDietRecord = catchAsync(async (req, res) => {
  // 如果userId应从当前登录用户获取，则应覆盖或校验req.body.userId
  // 例如: const recordBody = { ...req.body, userId: req.user.id };
  // 这里假设如果req.body.userId存在，则使用它（可能为管理员代录），否则使用req.user.id
  const userIdToUse = req.body.userId ? req.body.userId : req.user?.id;
  if (!userIdToUse || !mongoose.Types.ObjectId.isValid(userIdToUse)) {
    throw new ApiError(httpStatus.BAD_REQUEST, '有效的用户ID是必需的');
  }
  const recordBody = { ...req.body, userId: userIdToUse };

  const dietRecord = await dietRecordService.createDietRecord(recordBody);
  res.status(httpStatus.CREATED).send({
    error: 0,
    body: dietRecord,
    message: '饮食记录创建成功',
  });
});

const getDietRecords = catchAsync(async (req, res) => {
  const filter = pick(req.query, ['userId', 'mealType']);
  const options = pick(req.query, ['sortBy', 'limit', 'page', 'search']);

  // 处理日期范围筛选
  if (req.query.startDate) {
    filter.date = { ...filter.date, $gte: new Date(req.query.startDate) };
  }
  if (req.query.endDate) {
    filter.date = { ...filter.date, $lte: new Date(new Date(req.query.endDate).setHours(23, 59, 59, 999)) };
  }

  // 处理热量范围筛选
  if (req.query.minTotalCalories) {
    filter.totalCalories = { ...filter.totalCalories, $gte: parseInt(req.query.minTotalCalories, 10) };
  }
  if (req.query.maxTotalCalories) {
    filter.totalCalories = { ...filter.totalCalories, $lte: parseInt(req.query.maxTotalCalories, 10) };
  }

  const result = await dietRecordService.queryDietRecords(filter, options);
  res.send({
    error: 0,
    body: result,
    message: '饮食记录查询成功',
  });
});

const getDietRecord = catchAsync(async (req, res) => {
  const dietRecord = await dietRecordService.getDietRecordById(req.params.id);
  if (!dietRecord) {
    throw new ApiError(httpStatus.NOT_FOUND, '饮食记录未找到');
  }
  res.send({
    error: 0,
    body: dietRecord,
    message: '获取饮食记录详情成功',
  });
});

const updateDietRecord = catchAsync(async (req, res) => {
  // 确保不能通过此接口修改userId
  if (req.body.userId) {
    delete req.body.userId;
  }
  const dietRecord = await dietRecordService.updateDietRecordById(req.params.id, req.body);
  res.send({
    error: 0,
    body: dietRecord,
    message: '饮食记录更新成功',
  });
});

const deleteDietRecord = catchAsync(async (req, res) => {
  await dietRecordService.deleteDietRecordById(req.params.id);
  res.status(httpStatus.OK).send({ // 或者 httpStatus.NO_CONTENT
    error: 0,
    body: null,
    message: '饮食记录删除成功',
  });
});

const getDietRecordSummary = catchAsync(async (req, res) => {
  const queryOptions = pick(req.query, ['userId', 'date', 'period']); // period 可以是 day, week, month
  // 确保如果userId存在，则传递
  if (req.user && !queryOptions.userId) { 
    // 如果是普通用户查询自己的摘要，且query中没传userId，默认使用当前用户ID
    // 如果是管理员接口，并且允许查所有或指定用户，则逻辑会更复杂
    // 此处简化为：如果query有userId用query的，否则尝试用req.user.id (需认证)
    // queryOptions.userId = req.user.id;
  }

  const summary = await dietRecordService.getDietRecordSummary(queryOptions);
  res.send({
    error: 0,
    body: summary,
    message: '获取饮食记录摘要成功',
  });
});

module.exports = {
  createDietRecord,
  getDietRecords,
  getDietRecord,
  updateDietRecord,
  deleteDietRecord,
  getDietRecordSummary,
}; 